package me.macd.mindoc.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: mindoc
 * @description: ${description}
 * @author: 2018-09-29
 * @create: 2018-09-29 21:02
 */
public class Pagination {
    private HttpServletRequest request;
    private int total;
    private int perNum;

    public Pagination(HttpServletRequest request, int total, int perNum) {
        this.request = request;
        this.total = total;
        this.perNum = perNum;
    }

    public String Pages() {
        String page = request.getParameter("page");

        if (StringUtils.isBlank(page)) {
            page = "1";
        }

        int pageNum = Integer.parseInt(page);
        if (pageNum == 0) {
            return "";
        }

        int totalPageNum = (int) Math.ceil(total * 1.0 / perNum);

        String firstLink;
        String prevLink;
        String nextLink;
        String lastLink;
        List<String> pageLinks;

        if (pageNum > 1) {
            firstLink = String.format("<li><a href=\"%s\">首页</a></li>", pageUrl("1"));
            prevLink = String.format("<li><a href=\"%s\">上一页</a></li>", pageUrl((pageNum - 1) + ""));
        } else {
            firstLink = "<li class=\"disabled\"><a href=\"#\">首页</a></li>";
            prevLink = "<li class=\"disabled\"><a href=\"#\">上一页</a></li>";
        }

        if (pageNum < totalPageNum) {
            lastLink = String.format("<li><a href=\"%s\">末页</a></li>", pageUrl(totalPageNum + ""));
            nextLink = String.format("<li><a href=\"%s\">下一页</a></li>", pageUrl((pageNum + 1) + ""));
        } else {
            lastLink = "<li class=\"disabled\"><a href=\"#\">末页</a></li>";
            nextLink = "<li class=\"disabled\"><a href=\"#\">下一页</a></li>";
        }

        // 生成中间页码链接
        pageLinks = new ArrayList<>();
        int startPos = pageNum - 3;
        int endPos = pageNum + 3;
        if (startPos < 1) {
            endPos = endPos + Math.abs(startPos) + 1;
            startPos = 1;
        }
        if (endPos>totalPageNum) {
            endPos = totalPageNum;
        }
        for (int i=startPos;i<=endPos;i++) {
            String s;
            if (i==pageNum) {
                s = String.format("<li class=\"active\"><a href=\"%s\">%d</a></li>", pageUrl(i+""), i);
            } else {
                s = String.format("<li><a href=\"%s\">%d</a></li>", pageUrl(i+""), i);
            }
            pageLinks.add(s);
        }

        return String.format("<ul class=\"pagination\">%s%s%s%s%s</ul>", firstLink, prevLink, String.join("", pageLinks), nextLink, lastLink);
    }

    private String pageUrl(String page) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(request.getRequestURI()).append("?page=").append(page);
        return stringBuilder.toString();
    }
}
